package com.sh.shanhuo.adapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.sh.shanhuo.R;
import com.sh.shanhuo.activity.MainActivity;
import com.sh.shanhuo.database.sort.SortInfoDBUtils;
import com.sh.shanhuo.database.sort.SortInfoEntity;
import com.sh.shanhuo.database.web.WebInfoDBUtils;
import com.sh.shanhuo.database.web.WebInfoEntity;
import com.sh.shanhuo.dialog.CommonEditDialog;
import com.sh.shanhuo.listener.SimpleResultCallback;
import com.yanzhenjie.recyclerview.SwipeRecyclerView;

import java.util.Collections;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

public class SortAdapter extends RecyclerView.Adapter<SortAdapter.GroupViewHolder> {
    public final Context context;
    private static List<SortInfoEntity> sortInfoEntities;

    public SortAdapter(Context context) {
        this.context = context;
    }

    @SuppressLint("NotifyDataSetChanged")
    public void setGroupData(List<SortInfoEntity> entities) {
        sortInfoEntities = entities;
        notifyDataSetChanged();
    }

    public void itemMove(int fromPosition, int toPosition) {
        if (fromPosition < toPosition) {
            for (int i = fromPosition; i < toPosition; i++) {
                Collections.swap(sortInfoEntities, i, i + 1);
            }
        } else {
            for (int i = fromPosition; i > toPosition; i--) {
                Collections.swap(sortInfoEntities, i, i - 1);
            }
        }
        for (int i = 0; i < sortInfoEntities.size(); i++) {
            SortInfoEntity sortInfoEntity = sortInfoEntities.get(i);
            sortInfoEntity.sequence = i;
            SortInfoDBUtils.insertSortInfo(context, sortInfoEntity);
        }
        notifyItemMoved(fromPosition, toPosition);
    }

    @NonNull
    @Override
    public GroupViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View item = LayoutInflater.from(parent.getContext()).inflate(R.layout.sort_parent_view, parent, false);
        return new GroupViewHolder(item, context);
    }

    @Override
    public void onBindViewHolder(GroupViewHolder holder, int groupPosition) {
        String sortName = sortInfoEntities.get(groupPosition).sortName;
        List<WebInfoEntity> webInfoEntities = WebInfoDBUtils.getWebInfoBySortId(context, sortName);
        holder.sortTitle.setText(sortName);
        holder.childSize.setText(new StringBuilder().append("(").append(webInfoEntities.size()).append(")"));
        holder.close.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                if (webInfoEntities.size() > 0) {
                    holder.childView.setVisibility(View.VISIBLE);
                    holder.childViewAdapter.setChildData(webInfoEntities);
                }
            } else {
                holder.childView.setVisibility(View.GONE);
            }
        });
    }

    @Override
    public int getItemCount() {
        if (sortInfoEntities == null)
            return 0;
        return sortInfoEntities.size();
    }

    protected class GroupViewHolder extends RecyclerView.ViewHolder {

        private final CheckBox close;
        private final TextView sortTitle;
        private final TextView childSize;
        private final SwipeRecyclerView childView;
        private final ChildViewAdapter childViewAdapter;

        @SuppressLint("UseCompatLoadingForDrawables")
        public GroupViewHolder(View itemView, Context context) {
            super(itemView);
            close = itemView.findViewById(R.id.close);
            childSize = itemView.findViewById(R.id.childSize);
            sortTitle = itemView.findViewById(R.id.sortTitle);
            childView = itemView.findViewById(R.id.childView);
            RelativeLayout groupLayout = itemView.findViewById(R.id.groupLayout);
            groupLayout.setOnClickListener(v -> close.setChecked(!close.isChecked()));
            childViewAdapter = new ChildViewAdapter();
            childView.setItemAnimator(new DefaultItemAnimator());
            LinearLayoutManager manager = new LinearLayoutManager(context);
            manager.setOrientation(LinearLayoutManager.VERTICAL);
            childView.setLayoutManager(manager);
            childView.setAdapter(childViewAdapter);
            childView.setVisibility(close.isChecked() ? View.VISIBLE : View.GONE);
            childViewAdapter.setOnMoreClick((view, position) -> {
                if (childViewAdapter.webInfoEntities.get(position).onTop == 1
                        || childViewAdapter.webInfoEntities.get(position).serverTop == 1
                || childViewAdapter.webInfoEntities.get(position).webId.equals(MainActivity.fixedPushId)) {
                    Toast.makeText(context, "置顶或者常驻网址不可编辑", Toast.LENGTH_SHORT).show();
                    return;
                }
                CommonEditDialog.sort(context, view, new SimpleResultCallback() {
                    @Override
                    public void onResult(String data1, String data2) {

                    }

                    @Override
                    public void onButton(String action) {
                        if ("move".equals(action)) {
                            editSort(context, childViewAdapter.webInfoEntities.get(position), sortInfoEntities,
                                    new SimpleResultCallback() {
                                        @Override
                                        public void onResult(String data1, String data2) {
                                            List<WebInfoEntity> webInfoEntities =
                                                    WebInfoDBUtils.getWebInfoBySortId(context, data1);
                                            childViewAdapter.setChildData(webInfoEntities);
                                            List<SortInfoEntity> sortInfoEntities = SortInfoDBUtils.getAll(context);
                                            setGroupData(sortInfoEntities);
                                        }

                                        @Override
                                        public void onButton(String action) {

                                        }

                                        @Override
                                        public void onBean(Object obj) {

                                        }
                                    });
                        } else if ("delete".equals(action)) {
                            WebInfoEntity webInfoEntity = childViewAdapter.webInfoEntities.get(position);
                            if (webInfoEntity.permanent == 1) {
                                webInfoEntity.deleteFlag = 1;
                                WebInfoDBUtils.disableWebInfo(context, webInfoEntity);
                            } else {
                                WebInfoDBUtils.delete(context, webInfoEntity);
                            }
                            List<WebInfoEntity> webInfoEntities =
                                    WebInfoDBUtils.getWebInfoBySortId(context, sortInfoEntities.get(getAdapterPosition()).sortName);
                            childViewAdapter.setChildData(webInfoEntities);
                            List<SortInfoEntity> sortInfoEntities = SortInfoDBUtils.getAll(context);
                            setGroupData(sortInfoEntities);
                        }
                        close.setChecked(false);
                    }

                    @Override
                    public void onBean(Object obj) {

                    }
                });
            });
        }
    }

    //subView的adapter
    private static class ChildViewAdapter extends RecyclerView.Adapter<ChildViewAdapter.ChildViewHolder> {
        public List<WebInfoEntity> webInfoEntities;
        private OnMoreClickListener listener;

        @SuppressLint("NotifyDataSetChanged")
        public void setChildData(List<WebInfoEntity> webInfoEntities) {
            Collections.sort(webInfoEntities, (o1, o2) -> (int) (o1.updateTime - o2.updateTime));
            Collections.sort(webInfoEntities, (o1, o2) -> o2.onTop - o1.onTop);
            Collections.sort(webInfoEntities, (o1, o2) -> o2.serverTop - o1.serverTop);
            this.webInfoEntities = webInfoEntities;
            notifyDataSetChanged();
        }

        public ChildViewAdapter() {
        }

        public interface OnMoreClickListener {
            void moreClick(View view, int position);
        }

        public void setOnMoreClick(OnMoreClickListener listener) {
            this.listener = listener;
        }

        @NonNull
        @Override
        public ChildViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.sort_child_view, parent, false);
            return new ChildViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull ChildViewHolder holder, int childPosition) {
            if (childPosition == webInfoEntities.size() - 1) {
                holder.view.setVisibility(View.GONE);
            }
            int position = holder.getAdapterPosition();
            holder.sortTitle.setText(webInfoEntities.get(position).webName);
            holder.more.setOnClickListener(v -> {
                if (listener != null) {
                    listener.moreClick(v, position);
                }
            });
        }

        @Override
        public int getItemCount() {
            if (webInfoEntities == null)
                return 0;
            return webInfoEntities.size();
        }

        private static class ChildViewHolder extends RecyclerView.ViewHolder {
            private final TextView sortTitle;
            private final TextView view;
            private final ImageView more;

            private ChildViewHolder(View itemView) {
                super(itemView);
                sortTitle = itemView.findViewById(R.id.sortTitle);
                view = itemView.findViewById(R.id.view);
                more = itemView.findViewById(R.id.more);
            }
        }

    }

    private static void editSort(Context context, WebInfoEntity webInfoEntity, List<SortInfoEntity> sortInfoEntities,
                                 SimpleResultCallback callback) {
        CommonEditDialog.editSortDialog(context, webInfoEntity, sortInfoEntities, callback);
    }
}
